import * as redis from 'redis';
import { config } from '../config';
export class ReisHelper<V> {
    private redisClient: redis.RedisClient;
    constructor(redistStoreNum: number = 1) {
        this.redisClient = redis.createClient(<any>config.redisConfig.port, config.redisConfig.host);
        this.redisClient.select(redistStoreNum);
    }

    set(key: string, value: V) {
        if (value instanceof Object) {
            value = <any>JSON.stringify(value);
        }
        return new Promise<string>((resolve, reject) => {
            this.redisClient.set(<any>key, <any>value, (err, reply) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(reply);
                }
            })
        })
    }

    get(key: string): Promise<V> {
        return new Promise((resolve, reject) => {
            this.redisClient.get(<any>key, (err, reply) => {
                if (err) {
                    reject(err);
                }
                else {
                    try {
                        let r = JSON.parse(reply);
                        resolve(r);
                    } catch (error) {
                        resolve(<any>reply);
                    }
                }
            })
        })
    }

    delete(key: string) {
        this.redisClient.del(key);
    }

    forEach(fn) {
        this.redisClient.keys('*', async (err, reply) => {
            for (let key of reply) {
                let value = await this.get(key);
                fn(key, value);
            }
        })
    }
}